"""
数据库模型，表结构
"""
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime
from apps.database import DbModel
from passlib.hash import sha256_crypt
from datetime import datetime
from sqlalchemy.orm import relationship
"""
primary_key=True  主键
autoincrement=True  自增
unique=True         唯一的，不能重复
nullable=False     不能为空
"""

class User(DbModel):
    __tablename__ = 'user'  # 数据库表名
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), unique=True, nullable=False)
    password = Column(String(128), nullable=False)
    email = Column(String(64), nullable=True)
    address = Column(String(64), nullable=True)
    # uselist=False  设置一对一关系   backref 反向查询时候对象名称
    # project = relationship('Project', uselist=True, backref='user', cascade="all,delete")


class NewUser(DbModel):
    __tablename__ = 'new_user'  # 数据库表名
    id = Column(Integer, primary_key=True, autoincrement=True)
    username = Column(String(50), unique=True, nullable=False)
    password = Column(String(256), nullable=False)
    email = Column(String(64), nullable=True)
    # uselist=False  设置一对一关系   backref 反向查询时候对象名称
    project = relationship('Project', uselist=True, backref='new_user', cascade="all,delete")

    # 自动加密
    def hash_password(self, password):
        self.password = sha256_crypt.hash(password)

    # 校验密码
    def verify_password(self, password):
        """校验返回True  / False"""
        return sha256_crypt.verify(password, self.password)


class Project(DbModel):
    __tablename__ = 'project'  # 数据库表名
    id = Column(Integer, primary_key=True, autoincrement=True)
    project_name = Column(String(100), unique=True, nullable=False)
    publish_app = Column(String(100), nullable=True)
    project_desc = Column(String(600), nullable=True)
    # 所属用户
    user_id = Column(Integer, ForeignKey('new_user.id'))

    # 创建时间，更新时间
    create_time = Column(DateTime, default=datetime.now)
    update_time = Column(DateTime, onupdate=datetime.now, default=datetime.now)
